<?php

// phpMyRealty 3
//
// File Name: findlistings.php
// File Location : ./admin/
//
// Copyright (c)2009 phpMyRealty.com
//
// e-mail: support@phpMyRealty.com

// Include configuration file and general functions
define('PMR', 'true');
define('PMRADMIN', 'true');

include ( '.././config.php' );
include ( PATH . '/defaults.php' );

// ----------------------------------------------------------------------
// ADMIN SECTION / LISTINGS SEARCH

// Title tag content
$title = $lang['Property_Search'];

// Template header
include ( PATH . '/admin/template/header.php' );

// If logged we can start the page output
if (adminAuth($session->fetch('adminlogin'), $session->fetch('adminpassword')))

 {
  // Include navigation panel
  include ( PATH . '/admin/navigation.php' );
  // Make sure this administrator have access to this function
  adminPermissionsCheck('manage_listings', $session->fetch('adminlogin')) or error ('Critical Error', 'Incorrect privileges');

  // Approve Listing function
  if (isset($_GET['req']) && $_GET['req'] == 'approve' && isset($_GET['listingid']) && eregi('^[0-9]+$', $_GET['listingid']))
   {

    echo table_header ( $lang['Information'] );

    // Fetch the data for the listing
    $sql = 'SELECT approved, type, userid, title FROM ' . PROPERTIES_TABLE . ' WHERE id = "' . $_GET['listingid'] . '" LIMIT 1';
    $r = $db->query($sql) or error ( 'Critical Error', mysql_error() );
    $f = $db->fetcharray($r);

    // If this listing was not approved yet we start
    if ($f['approved'] != 1)
     {
 
      $sql = 'UPDATE ' . PROPERTIES_TABLE . ' SET date_approved = NOW(), approved = "1" WHERE id = "' . $_GET['listingid'] . '" LIMIT 1';  
      $db->query($sql) or error ( 'Critical Error', mysql_error() );
      // Add listing to category counters
      update_categories ('', $f['type']);

//

      $mail = new PHPMailer();

      if(PHPMAILER == '3') {
       $mail->IsSMTP(); // set mailer to use SMTP
       $mail->Host = $smtp['host'];  // specify main and backup server
       $mail->SMTPAuth = true;     // turn on SMTP authentication
       $mail->Username = $smtp['login'];  // SMTP username
       $mail->Password = $smtp['password']; // SMTP password
      }
      elseif(PHPMAILER == '2') {
       $mail->IsSendmail(); // set mailer to use SMTP
      }
      else {
      }

      $mail->From = $conf['general_e_mail'];
      $mail->FromName = $conf['general_e_mail_name'];

      $sql = 'SELECT * FROM ' . USERS_TABLE  . ' WHERE id = "' . $f['userid'] . '" LIMIT 1';
      $r_user = $db->query ( $sql ) or error ('Critical Error' , mysql_error());
      $f_user = $db->fetcharray ($r_user);

      $mail->AddAddress($f_user['email']);

      $lang['User_Listing_Notification_Subject'] = str_replace('{website_name}', $conf['website_name'], $lang['User_Listing_Notification_Subject']);

      $mail->Subject = $lang['User_Listing_Notification_Subject'];

      // Replacing the variable names
      $lang['User_Listing_Notification_Mail'] = str_replace('{website_name}', $conf['website_name'], $lang['User_Listing_Notification_Mail']);
      $lang['User_Listing_Notification_Mail'] = str_replace('{title}', $f['title'], $lang['User_Listing_Notification_Mail']);

      $mail->MsgHTML    = $lang['User_Listing_Notification_Mail'];
      $mail->AltBody = removehtml($lang['User_Listing_Notification_Mail']);

      $mail->Send();

     }


      // Send email alerts to all subscribers

      // Fetch the data for the listing
      $sql = 'SELECT * FROM ' . PROPERTIES_TABLE . ' WHERE id = "' . $_GET['listingid'] . '" LIMIT 1';
      $re = $db->query($sql) or error ( 'Critical Error', mysql_error() );
      $fe = $db->fetcharray($re);

      $r = $db->query ('SELECT * FROM ' . ALERTS_TABLE . ' WHERE
                        type = "' . $fe['type'] . '" AND
		        city = "' . $fe['location2'] . '" AND
		        zip = "' . $fe['zip'] . '" AND
			approved = 1');

      while ($f = $db->fetcharray($r)) {
 
       $mail = new PHPMailer();

       if(PHPMAILER == '3') {
        $mail->IsSMTP(); // set mailer to use SMTP
        $mail->Host = $smtp['host'];  // specify main and backup server
        $mail->SMTPAuth = true;     // turn on SMTP authentication
        $mail->Username = $smtp['login'];  // SMTP username
        $mail->Password = $smtp['password']; // SMTP password
       }
       elseif(PHPMAILER == '2') {
        $mail->IsSendmail(); // set mailer to use SMTP
       }
       else {
       }

       $mail->From = $conf['general_e_mail'];
       $mail->FromName = $conf['general_e_mail_name'];

       $mail->AddAddress($f['email']);

       $lang['Alert_Subject'] = str_replace('{website}', $conf['website_name'], $lang['Alert_Subject']);
     
       $mail->Subject = $lang['Alert_Subject'];

       // Replacing the variable names
       $lang['Alert_Mail'] = str_replace('{name}', $f['name'], $lang['Alert_Mail']);
       $lang['Alert_Mail'] = str_replace('{link}', URL . '/viewlisting.php?id=' . $fe['id'], $lang['Alert_Mail']);
       $lang['Alert_Mail'] = str_replace('{unsubscribe}', URL . '/alertscontrol.php?req=unsubscribe&code=' . $f['code'], $lang['Alert_Mail']);
       $lang['Alert_Mail'] = str_replace('{website}', $conf['website_name'], $lang['Alert_Mail']);

       $mail->MsgHTML = $lang['Alert_Mail'];
       $mail->AltBody = removehtml($lang['Alert_Mail']);

       $mail->Send();

      }

    echo $lang['Admin_Listing_Approved'];

    echo table_footer ();

   }

  // Remove Listing function
  if (isset($_GET['req']) && $_GET['req'] == 'remove' && isset($_GET['listingid']) && eregi('^[0-9]+$', $_GET['listingid']))

   {

    // Fetch the data for the listing
    $sql = 'SELECT approved, type, userid FROM ' . PROPERTIES_TABLE . ' WHERE id = "' . $_GET['listingid'] . '" LIMIT 1';
    $r = $db->query($sql) or error ( 'Critical Error', mysql_error() );
    $f = $db->fetcharray($r);

    echo table_header ( $lang['Information'] );

    $sql = 'SELECT * FROM ' . USERS_TABLE  . ' WHERE id = "' . $f['userid'] . '" LIMIT 1';
    $r_user = $db->query ( $sql ) or error ('Critical Error' , mysql_error());
    $f_user = $db->fetcharray ($r_user);

    removelisting(intval($_GET['listingid']));

    echo $lang['Admin_Listing_Removed'];

//

    $mail = new PHPMailer();

    if(PHPMAILER == '3') {
     $mail->IsSMTP(); // set mailer to use SMTP
     $mail->Host = $smtp['host'];  // specify main and backup server
     $mail->SMTPAuth = true;     // turn on SMTP authentication
     $mail->Username = $smtp['login'];  // SMTP username
     $mail->Password = $smtp['password']; // SMTP password
    }
    elseif(PHPMAILER == '2') {
     $mail->IsSendmail(); // set mailer to use SMTP
    }
    else {
    }

    $mail->From = $conf['general_e_mail'];
    $mail->FromName = $conf['general_e_mail_name'];

    $mail->AddAddress($f_user['email']);

    $lang['User_Rejected_Notification_Subject'] = str_replace('{website_name}', $conf['website_name'], $lang['User_Rejected_Notification_Subject']);

    $mail->Subject = $lang['User_Rejected_Notification_Subject'];

    // Replacing the variable names
    $lang['User_Rejected_Notification_Mail'] = str_replace('{website_name}', $conf['website_name'], $lang['User_Rejected_Notification_Mail']);

    $mail->MsgHTML    = $lang['User_Rejected_Notification_Mail'];
    $mail->AltBody = removehtml($lang['User_Rejected_Notification_Mail']);

    $mail->Send();

    echo table_footer ();

   }


  // Define an array of all the search elements
  $search = array();

  // If this is the first time we call this script
  // we use the _POST'ed variable, if not, we use
  // _GET method
  if (isset($_POST['property_search']))
   {
    if (isset($_POST['buildings']) && is_array($_POST['buildings']) )
     $_POST['buildings'] = implode (':', $_POST['buildings']);

    if (isset($_POST['appliances']) && is_array($_POST['appliances']) )
     $_POST['appliances'] = implode (':', $_POST['appliances']);

    if (isset($_POST['features']) && is_array($_POST['features']) )
     $_POST['features'] = implode (':', $_POST['features']);

    $search = array_map ('safehtml', $_POST);
   }
  else
   {
    $search = array_map ('rawurldecode', $_GET);
    $search = array_map ('safehtml', $search);
   }   

  // Generate GET vars and push it into the session variable
  // to be able to return to this search page later

  unset ($search['req']);
  unset ($search['listingid']);

  $session->varunset('listingsearchvariables');
  $searchURL = ''; foreach ($search as $key => $value) $searchURL.= $key . '=' . rawurlencode($value) . '&';
  $session->set('listingsearchvariables', $searchURL);

  // Pagination
  if (isset($_GET['page'])) $page = $_GET['page']; else $page = 0;
  unset($search['page']);

  $results_page = $page * $conf['search_results'];

  // Errors output if needed

  // Initially we think that no errors were found
  $count_error = 0;

/*

// If keyword was not specified we stop processing
if (isset($search['description']) && empty($search['description']))
 { echo $lang['Field_Empty'] . ' <strong><span class="warning">' . $lang['Search_Keyword'] . '</span></strong><br />'; $count_error++; }
//

*/

  // If there were errors found we print the 
  // errors descriptions
  if ($count_error != 0)
   {
    echo table_header ( $lang['Information'] );

    echo $lang['Errors_Found'] . ': ' . $count_error;

    echo table_footer ();
   }

  // Output the results
  //
  // If no errors found we output the results

  $listingsearch = $session->fetch('listingsearchvariables');

  if ($count_error == 0 && !empty($listingsearch))
   {
   
	// Title/descr language to use (if available)
	$title = str_replace( 'name', 'title', $language_in );
	$description = str_replace( 'name', 'description', $language_in );

    // Generate the SQL query
    $sql = 'SELECT ' . $title . ', ' . $description . ', ' . PROPERTIES_TABLE . '.* FROM ' . PROPERTIES_TABLE  . ' WHERE ';

    $sql.= ' id IS NOT NULL ';

    if (isset($search['listing_approved']) && !empty($search['listing_approved'])) 
     $sql.= 'AND approved = "0" ';

    if (isset($search['listing_expired']) && !empty($search['listing_expired'])) 
     $sql.= 'AND approved = "2" ';

    if (isset($search['listing_updated']) && !empty($search['listing_updated']) && isset($search['listing_updated_days']) && !empty($search['listing_updated_days']))
     $sql.= 'AND ( (TO_DAYS(NOW()) - TO_DAYS(date_updated)) <= "' . $search['listing_updated_days']. '" ) ';

    if (isset($search['userid']) && !empty($search['userid'])) 
     $sql.= ' AND userid = "' . $search['userid'] . '" ';

    if (isset($search['id']) && !empty($search['id'])) 
     $sql.= ' AND id = "' . $search['id'] . '" ';

    if (isset($search['mls']) && !empty($search['mls'])) 
     $sql.= ' AND mls = "' . $search['mls'] . '"';

    if (isset($search['title']) && !empty($search['title'])) 
     $sql.= ' AND title LIKE "%' . $search['title'] . '%" ';

    if (isset($search['type']) && $search['type'] != 'ANY') 
     $sql.= ' AND type = "' . $search['type'] . '" ';

    if (isset($search['style']) && $search['style'] != 'ANY') 
     $sql.= ' AND style = "' . $search['style'] . '" ';

    if (isset($search['type2']) && $search['type2'] != 'ANY') 
     $sql.= ' AND type2 = "' . $search['type2'] . '" ';

    if (isset($search['keyword']) && !empty($search['keyword'])) 
     $sql.= ' AND description LIKE "%' . $search['keyword'] . '%" ';

    if (isset($search['size']) && !empty($search['size'])) 
     $sql.= ' AND size = "' . $search['keyword'] . '" ';
 
    if (isset($search['dimensions']) && !empty($search['dimensions'])) 
     $sql.= ' AND dimensions = "' . $search['dimensions'] . '" ';

    if (isset($search['bathrooms']) && !empty($search['bathrooms'])) 
     $sql.= ' AND bathrooms = "' . $search['bathrooms'] . '" ';

    if (isset($search['half_bathrooms']) && !empty($search['half_bathrooms'])) 
     $sql.= ' AND half_bathrooms = "' . $search['half_bathrooms'] . '" ';

    if (isset($search['bedrooms']) && !empty($search['bedrooms'])) 
     $sql.= ' AND bedrooms = "' . $search['bedrooms'] . '" ';
 
    if (isset($search['location2']) && $search['location2'] != 'ANY')
     $sql.= ' AND location2 = "' . $search['location2'] . '" ';

    if (isset($search['city']) && !empty($search['city'])) 
     $sql.= ' AND city = "' . $search['city'] . '" ';

    if (isset($search['zip']) && !empty($search['zip'])) 
     $sql.= ' AND zip = "' . $search['zip'] . '" ';

    if (isset($search['address']) && !empty($search['address'])) 
     {
      $sql.= 'AND (address1 LIKE "%' . $search['address'] . '%" ';
      $sql.= ' OR address2 LIKE "%' . $search['address'] . '%" ) ';
     }

    if (isset($search['price_max']) && isset($search['price_min']))
     {

      if ($search['price_max'] != 'ANY' && $search['price_min'] == 'ANY') 
       $sql.= ' AND price <= "' . $search['price_max'] . '" ';

      if ($search['price_max'] == 'ANY' && $search['price_min'] != 'ANY') 
	$sql.= ' AND price >= "' . $search['price_min'] . '" ';

      if ($search['price_max'] != 'ANY' && $search['price_min'] != 'ANY') 
	$sql.= ' AND price >= "' . $search['price_min'] . '" AND price <= "' . $search['price_max'] . '" ';
     }

    if (isset($search['directions']) && !empty($search['directions'])) 
     $sql.= ' AND directions LIKE "%' . $search['directions'] . '%" ';

    if (isset($search['year_built']) && !empty($search['year_built'])) 
     $sql.= ' AND year_built = "' . $search['year_built'] . '" ';

    // BUILDINGS

    if (isset($search['buildings']) && !empty($search['buildings'])) 
     {

      if (strstr($search['buildings'], ':'))
       {

 	$search_buildings2 = explode (':', $search['buildings']);
	foreach($search_buildings2 as $search_buildings)
 	 {
	  $sql.= ' AND (buildings LIKE "%:' . $search_buildings . ':%" 
		   OR buildings LIKE "%:' . $search_buildings . '"  
		   OR buildings LIKE "' . $search_buildings . ':%" 
		   OR buildings LIKE "' . $search_buildings . '" ) ';
	  $i++;
	 }

       }

      else

       $sql.= ' AND (buildings LIKE "%:' . $search['buildings'] . ':%" 
	        OR buildings LIKE "%:' . $search['buildings'] . '"  
	        OR buildings LIKE "' . $search['buildings'] . ':%" 
		OR buildings LIKE "' . $search['buildings'] . '" ) ';
     }

    // APPLIANCES
    if (isset($search['appliances']) && !empty($search['appliances'])) 
     {

      if (strstr($search['appliances'], ':'))
	{

 	 $search_appliances2 = explode (':', $search['appliances']);
	 foreach($search_appliances2 as $search_appliances)
	  {
	   $sql.= ' AND (appliances LIKE "%:' . $search_appliances . ':%" 
		    OR appliances LIKE "%:' . $search_appliances . '"  
		    OR appliances LIKE "' . $search_appliances . ':%" 
		    OR appliances LIKE "' . $search_appliances . '" ) ';
	  }	 
        }

       else

	{

 	 $sql.= ' AND (appliances LIKE "%:' . $search['appliances'] . ':%" 
		  OR appliances LIKE "%:' . $search['appliances'] . '"  
		  OR appliances LIKE "' . $search['appliances'] . ':%" 
		  OR appliances LIKE "' . $search['appliances'] . '" ) ';
	}

     }

    // FEATURES
    if (isset($search['features']) && !empty($search['features'])) 
     {

      if (strstr($search['features'], ':'))
       {

 	$search_features2 = explode (':', $search['features']);
	foreach($search_features2 as $search_features)
 	 {
	  $sql.= ' AND (features LIKE "%:' . $search_features . ':%" 
		   OR features LIKE "%:' . $search_features . '"  
		   OR features LIKE "' . $search_features . ':%" 
		   OR features LIKE "' . $search_features . '" ) ';
	 }
       }

      else

       $sql.= ' AND (features LIKE "%:' . $search['features'] . ':%" 
		OR features LIKE "%:' . $search['features'] . '"  
		OR features LIKE "' . $search['features'] . ':%" 
		OR features LIKE "' . $search['features'] . '" ) ';
     }

    if (isset($search['garage']) && $search['garage'] != 'ANY') 
     $sql.= ' AND garage = "' . $search['garage'] . '" ';

    if (isset($search['garage_cars']) && !empty($search['garage_cars'])) 
     $sql.= ' AND garage_cars = "' . $search['garage_cars'] . '" ';

    if (isset($search['basement']) && $search['basement'] != 'ANY') 
     $sql.= ' AND basement = "' . $search['basement'] . '" ';

    // Generate sql2 query which inlcudes LIMIT and ORDER BY functions
    $sql2 = $sql;

    if (isset($search['order_by']) && $search['order_by'] != 'ANY') 
     $sql2.= ' ORDER BY ' . $search['order_by'] . ' ';

if (
isset($search['order_by_type']) &&
($search['order_by_type'] != 'ANY' 
&& $search['order_by_type'] != 'DESC' 
&& $search['order_by_type'] != 'ASC')
)
die ('Hacking Attempt');

    if (isset($search['order_by']) && $search['order_by'] != 'ANY' 
    && isset($search['order_by_type']) && $search['order_by_type'] != 'ANY' ) 
     $sql2.= $search['order_by_type'];

    $sql2.=  ' LIMIT ' . $results_page . ', ' . $conf['search_results'];
    
    // End creating sql query

    // Navigation
    echo table_header ( $lang['Navigation'] );

    $usersearch = $session->fetch('usersearchvariables');
    $listingsearch = $session->fetch('listingsearchvariables');
    // Back to the user search page using the cached search values
    if (!empty($usersearch))
     echo '- <a href="' . URL . '/admin/findusers.php?' . $session->fetch('usersearchvariables') . '">' . $lang['Search_Back_User'] . '</a><br />';

    // Back to the listing search page using the cached search values
    if (!empty($listingsearch))
     echo '- <a href="' . URL . '/admin/findlistings.php?' . $session->fetch('listingsearchvariables') . '">' . $lang['Search_Back_Listing'] . '</a><br />';

    echo table_footer ();

    //

    echo table_header ( $lang['Property_Search'] );

    echo '
     <table width="100%" cellpadding="5" cellspacing="0" border="0">
         ';

    $r = $db->query($sql) or error ('Critical Error', mysql_error ());

    $r2 = $db->query($sql2) or error ('Critical Error', mysql_error ());

    if ($db->numrows($r) == 0)
     echo '<p align="center"><span class="warning">' . $lang['Nothing_Found'] . '</span></p>';

    $i = 0;

    $tpl = implode ('', file( PATH . '/admin/template/tpl/listing-short.tpl' ));

    while ($f = $db->fetcharray( $r2 ))

     {

      // Starting a new template
      $template = new Template;

      // Load listing short search results template
      $template->load ( $tpl );
 
      $f = array_map ( 'if_empty', $f);
 
      // Replace the template variables
 
	// Default
	if ($f[0] == '')
		$f['title'] = $f['title'];
	else
		$f['title'] = $f[0];
		
	if ($f[1] == '')
		$f['description'] = $f['description'];
	else
		$f['description'] = $f[1];
 
      if (($f['approved'] == 0 || $f['approved'] == 2) && adminPermissionsCheck('manage_listings', $session->fetch('adminlogin')))
       $template->set ( 'approve', '<a href="' . URL . '/admin/findlistings.php?req=approve&listingid=' . $f['id'] . '&' . $session->fetch('listingsearchvariables') . '">' . $lang['Admin_Approve_This'] . '</a>');
      else
       $template->set ( 'approve', $lang['Admin_Approve_This']);

      $template->set ( 'edit',  '<a href="' . URL . '/admin/editlistings.php?id=' . $f['id'] . '&' . $session->fetch('listingsearchvariables') . '">' . $lang['Admin_Edit_This'] . '</a>');
      $template->set ( 'remove', '<a href="' . URL . '/admin/findlistings.php?req=remove&listingid=' . $f['id'] . '&' . $session->fetch('listingsearchvariables') . '"><span class="warning">' . $lang['Admin_Remove_This'] . '</span></a>');

      $sql = 'SELECT COUNT(*) FROM ' . GALLERY_TABLE . ' WHERE listingid = ' . $f['id'];
      $res = $db->query($sql); 
      $gallery = mysql_result ($res, 0, 0);
 
      if (adminPermissionsCheck('manage_gallery', $session->fetch('adminlogin')))
       $template->set ( 'edit_gallery', '<a href="' . URL . '/admin/editgallery.php?id=' . $f['id'] . '&userid=' . $f['userid'] . '">' . $lang['Photo_Gallery'] . '</a> (' . $gallery . ')');
      else
       $template->set ( 'edit_gallery', $lang['Photo_Gallery']);

      $template->set ( 'image', show_image ('images', $f['id']) );
      $template->set ( 'mls', $f['mls'] );
      $template->set ( 'title', $f['title'] );
      $template->set ( 'type', getnamebyid ( TYPES_TABLE, $f['type'] ) );
      $template->set ( 'type2', getnamebyid ( TYPES2_TABLE, $f['type2'] ) );
      $template->set ( 'style', getnamebyid ( STYLES_TABLE, $f['style'] ) );
  
      $description = substr($f['description'], 0, $conf['search_description']);
      $description = substr($description, 0, strrpos($description, ' ')) . ' ... ';
 
      $template->set ( 'description', removehtml(unsafehtml($description)) );
      
      unset ($description);
 
      $template->set ( 'lot_size', $f['size'] );
      $template->set ( 'dimensions', $f['dimensions'] );
      $template->set ( 'bathrooms', $f['bathrooms'] );
      $template->set ( 'half_bathrooms', $f['half_bathrooms'] );
      $template->set ( 'bedrooms', $f['bedrooms'] );

      $cat = explode ("#", $f['location2']);
      $r11 = $db->query('SELECT category FROM ' . LOCATION1_TABLE . ' WHERE selector = "' . $cat[0] . '"');
      $f11 = $db->fetcharray($r11);
      $template->set ( 'location1', $f11['category'] );

      $r22 = $db->query('SELECT subcategory FROM ' . LOCATION2_TABLE . ' WHERE catsubsel = "' . $cat[1] . '"');
      $f22 = $db->fetcharray($r22);
      $template->set ( 'location2', $f22['subcategory'] );

      $r33 = $db->query('SELECT subsubcategory FROM ' . LOCATION3_TABLE . ' WHERE catsubsubsel = "' . $cat[2] . '"');
      $f33 = $db->fetcharray($r33);
      $template->set ( 'location3', $f33['subsubcategory'] );
  
      if ($f['display_address'] == 'YES')
       {
        $template->set ( 'address1', $f['address1'] );
        $template->set ( 'address2', $f['address2'] );
        $template->set ( 'zip', $f['zip'] );
       }
      else
       {
        $template->set ( 'address1', ' ' );
        $template->set ( 'address2', ' ' );
        $template->set ( 'zip', ' ' );
       }
 
      $template->set ( 'price', pmr_number_format($f['price']) );
      $template->set ( 'currency', $conf['currency'] );
      $template->set ( 'directions', $f['directions'] );
      $template->set ( 'year_built', $f['year_built'] );
      $template->set ( 'buildings', show_multiple ( BUILDINGS_TABLE, $f['buildings'] ) );
      $template->set ( 'appliances', show_multiple ( APPLIANCES_TABLE, $f['appliances'] ) );
      $template->set ( 'features', show_multiple ( FEATURES_TABLE, $f['features'] ) );
      $template->set ( 'garage', getnamebyid ( GARAGE_TABLE, $f['garage'] ) );
      $template->set ( 'garage_cars', $f['garage_cars'] );
      $template->set ( 'basement', getnamebyid ( BASEMENT_TABLE, $f['basement'] ) );
  
      $template->set ( 'date_added', printdate($f['date_added']) );
      $template->set ( 'date_updated', printdate($f['date_updated']) );
      $template->set ( 'date_upgraded', printdate($f['date_upgraded']) );
 
      $template->set ( 'ip_added', $f['ip_added'] );
      $template->set ( 'ip_updated', $f['ip_updated'] );
      $template->set ( 'ip_upgraded', $f['ip_upgraded'] );
  
      $template->set ( 'hits', $f['hits'] );
  
      $template->set ( 'new', newitem ( PROPERTIES_TABLE, $f['id'], $conf['new_days']) );
      $template->set ( 'updated', updateditem ( PROPERTIES_TABLE, $f['id'], $conf['updated_days']) );
      $template->set ( 'featured', featureditem ( $f['featured'] ) );
  
      $sql = 'SELECT * FROM ' . USERS_TABLE  . ' WHERE approved = 1 AND id = ' . $f['userid'] . ' LIMIT 1';
      $r_user = $db->query ( $sql ) or error ('Critical Error' , mysql_error());
      $f_user = $db->fetcharray ($r_user);
 
      $template->set ( 'view_realtor', '<a href="' . URL . '/admin/findusers.php?id=' . $f['userid'] . '">' . $f_user['first_name'] . ' ' . $f_user['last_name'] . '</a>');
  
      // Names
 
      $template->set ( '@mls', $lang['Listing_MLS'] );
      $template->set ( '@title', $lang['Listing_Title'] );
      $template->set ( '@type', $lang['Listing_Property_Type'] );
      $template->set ( '@type2', $lang['Module_Listing_Type'] );
      $template->set ( '@style', $lang['Listing_Style'] );
      $template->set ( '@description', $lang['Listing_Description'] );
      $template->set ( '@lot_size', $lang['Listing_Lot_Size'] );
      $template->set ( '@dimensions', $lang['Listing_Dimensions'] );
      $template->set ( '@bathrooms', $lang['Listing_Bathrooms'] );
      $template->set ( '@half_bathrooms', $lang['Listing_Half_Bathrooms'] );
      $template->set ( '@bedrooms', $lang['Listing_Bedrooms'] );
      $template->set ( '@location', $lang['Search_Location'] );
      $template->set ( '@city', $lang['City'] );
      $template->set ( '@address1', $lang['Listing_Address1'] );
      $template->set ( '@address2', $lang['Listing_Address2'] );
      $template->set ( '@zip', $lang['Zip_Code'] );
      $template->set ( '@price', $lang['Listing_Price'] );
      $template->set ( '@directions', $lang['Listing_Directions'] );
      $template->set ( '@year_built', $lang['Listing_Year_Built'] );
      $template->set ( '@buildings', $lang['Listing_Additional_Out_Buildings'] );
      $template->set ( '@appliances', $lang['Listing_Appliances_Included'] );
      $template->set ( '@features', $lang['Listing_Features'] );
      $template->set ( '@garage', $lang['Listing_Garage'] );
      $template->set ( '@garage_cars', $lang['Listing_Garage_Cars'] );
      $template->set ( '@basement', $lang['Listing_Basement'] );
  
      $template->set ( '@date_added', $lang['Date_Added'] );
      $template->set ( '@date_updated', $lang['Date_Updated'] );
      $template->set ( '@date_upgraded', $lang['Date_Upgraded'] );
  
      $template->set ( '@hits', $lang['Hits'] );
  
      $template->set ( '@view_realtor', $lang['View_Realtor'] );
 
      // Set background color
      $bgcolor = ''; // Background color for all odd listings
      $bgcolor2 = $conf['list_background_color_even']; // Background color for all even listings
  
      if ( $i%2 == 0 )
       $template->set ( 'bgcolor', $bgcolor );
      else
       $template->set ( 'bgcolor', $bgcolor2 );
  
      // Publish template
      $template->publish();
 
      $i++;
 
     }
 
    echo '
     </table>
         ';
 
    // Pagination
 
    echo '<br />';
 
    // Generate GET vars and push it into the variable
    $searchURL = ''; foreach ($search as $key => $value) $searchURL.= $key . '=' . rawurlencode($value) . '&';
 
    $results = $db->numrows( $r );
 
    if ( $results > $conf['search_results'] )
 
     {
 
      if ((($page*$conf['search_results'])-($conf['search_results']*5)) >= 0) 
       $first=($page*$conf['search_results'])-($conf['search_results']*5);
      else 
       $first=0;
 
      if ((($page*$conf['search_results'])+($conf['search_results']*6)) <= $results) 
       $last =($page*$conf['search_results'])+($conf['search_results']*6);
      else 
       $last = $results;
 
      @    $i=$first/$conf['search_results'];

      // Previous
      if ($page > 0)
       {
        $pagenum = $page - 1;
        echo ' <a href="' . URL . '/admin/findlistings.php?page=' . $pagenum . '&' . $searchURL . '">' . $lang['Previous'] . '</a> | ';
       }
 
      // Pagination
      for ( $step = $first; $step < $last; $step=$step+$conf['search_results'] )
       {
 
        if ( $i == $page )
 
   	 {
 	  $pagenum = $i+1;
 	  echo ' <span class="warning">' . $pagenum . '</span> | ';
 	  $i++;
 	 }
 
        else
 
 	 {
 
 	  $pagenum = $i+1;
	  echo ' <a href="' . URL . '/admin/findlistings.php?page=' . $i . '&' . $searchURL . '">' . $pagenum . '</a> | ';
	  $i++;

	 }

       }

      // Next
      if ($page - (($results / $conf['search_results']) - 1) < 0)
       {
        $pagenum = $page+1;
        echo ' <a href="' . URL . '/admin/findlistings.php?page=' . $pagenum . '&' . $searchURL . '">' . $lang['Next'] . '</a>';
       }
 
     }
 
    // Pagination : END
  
    echo table_footer ();
 
   }
  
  // Output the Find Property form
 
  echo table_header ( $lang['Property_Search'] );
 
  echo '
   <form action="' . URL . '/admin/findlistings.php" method="POST">
    <table width="100%" cellpadding="5" cellspacing="0" border="0">
       ';
 
  echo userform ($lang['Listing_Approved'], '<input type="checkbox" name="listing_approved" value="YES">');
  echo userform ($lang['Listing_Show_Updated'], '<input type="checkbox" name="listing_updated" value="YES"> ' . $lang['Listing_Show_Updated_For_The_Last'] . ' <input type="text" size="3" name="listing_updated_days" value="5" maxlength="3">' . $lang['days']);
  
  $order_options = '
 
  <option value="mls">' . $lang['Listing_MLS'] . '</option>
  <option value="title">' . $lang['Listing_Title'] . '</option>
  <option value="price">' . $lang['Listing_Price'] . '</option>
  <option value="size">' . $lang['Listing_Lot_Size'] . '</option>
  <option value="dimensions">' . $lang['Listing_Dimensions'] . '</option>
  <option value="bathrooms">' . $lang['Listing_Bathrooms'] . '</option>
  <option value="half_bathrooms">' . $lang['Listing_Half_Bathrooms'] . '</option>
  <option value="bedrooms">' . $lang['Listing_Bedrooms'] . '</option>
  <option value="city">' . $lang['City'] . '</option>
  <option value="zip">' . $lang['Zip_Code'] . '</option>
  <option value="year_built">' . $lang['Listing_Year_Built'] . '</option>
  <option value="garage_cars">' . $lang['Listing_Garage_Cars'] . '</option>
  <option value="date_added">' . $lang['Date_Added'] . '</option>
  <option value="date_updated">' . $lang['Date_Updated'] . '</option>
  
 	 	 ';
 
  $order_type_options = '
 
  <option value="ASC">' . $lang['Listing_Ascending'] . '</option>
  <option value="DESC">' . $lang['Listing_Descending'] . '</option>
  
   		        ';
  
  echo userform ($lang['Order_By'], '<select name="order_by"><option value="ANY">' . $lang['Search_Any'] . '</option>' . $order_options . '</select> <select name="order_by_type"><option value="ANY">' . $lang['Search_Any'] . '</option>' . $order_type_options . '</select>');
  echo userform ($lang['Module_Listing_Type'], '<select name="type2"><option value="ANY">' . $lang['Search_Any'] . '</option>' . generate_options_list(TYPES2_TABLE) . '</select>');
  if (strcasecmp(@$conf['show_mls'], 'OFF') != 0) {
      echo userform ($lang['Listing_MLS'], '<input type="text" size="45" name="mls" maxlength="46" />');
  }
  echo userform ($lang['Listing_Title'], '<input type="text" size="45" name="title" maxlength="50">');
  echo userform ($lang['Listing_Property_Type'], '<select name="type"><option value="ANY">' . $lang['Search_Any'] . '</option>' . generate_options_list(TYPES_TABLE) . '</select>');
  echo userform ($lang['Listing_Style'], '<select name="style"><option value="ANY">' . $lang['Search_Any'] . '</option>' . generate_options_list(STYLES_TABLE) . '</select>');
  echo userform ($lang['Search_Keyword'], '<input type="text" size="45" name="keyword" maxlength="50">');
  echo userform ($lang['Listing_Lot_Size'], '<input type="text" size="45" name="size" maxlength="50">');
  echo userform ($lang['Listing_Dimensions'], '<input type="text" size="45" name="dimensions" maxlength="50">');
  echo userform ($lang['Listing_Bathrooms'], '<input type="text" size="45" name="bathrooms" maxlength="2">');
  echo userform ($lang['Listing_Half_Bathrooms'], '<input type="text" size="45" name="half_bathrooms" maxlength="2">');
  echo userform ($lang['Listing_Bedrooms'], '<input type="text" size="45" name="bedrooms" maxlength="2">');

  // ==


  $in_location = '<select name="location2"><option value="ANY">' . $lang['Search_Any'] . '</option>';

  $category_list = '';

  $re = $db->query  ( 'SELECT * FROM ' . LOCATION1_TABLE . ' ORDER BY category' ) or die (mysql_error());

  $results_amount1 = mysql_numrows($re);

  for($i = 0; $i < $results_amount1; $i++) {
   $fe = $db->fetcharray ($re);
   $ree = $db->query  ( 'SELECT * FROM ' . LOCATION2_TABLE . ' WHERE catsel = ' . $fe['selector'] . ' ORDER BY subcategory');
   $results_amount2 = mysql_numrows($ree);
   if ($results_amount2 == 0) $results_amount2=1;
   for($j=0; $j < $results_amount2; $j++) {
    $fee = $db->fetcharray ($ree);
    $reee = $db->query  ( 'SELECT * FROM ' . LOCATION3_TABLE . ' WHERE catsel= ' . $fe['selector'] . ' AND catsubsel = ' . $fee['catsubsel'] . ' ORDER BY subsubcategory');
    @$results_amount3 = mysql_numrows($reee);

    if (($results_amount2 == 0) and ($results_amount3 == 0)) $results_amount3 = 1;
    if (($results_amount2 != 0) and ($results_amount3 == 0)) $results_amount3 = 1;

    for($k = 0; $k < $results_amount3; $k++) {

     @$feee=$db->fetcharray ($reee);
     $found= "0";
     if (!isset($fee['catsubsel'])) $fee['catsubsel']=0;
     if (!isset($feee['catsubsubsel'])) $feee['catsubsubsel']=0;
    if ($category_list == $fe['selector'] . '#' . $fee['catsubsel'] . '#' . $feee['catsubsubsel']) {
     $found = "1"; }
    if ($found == "1") {
     if (($feee['catsubsubsel'] != 0) and ($fee['catsubsel'] != 0))
       $in_location .= '<OPTION VALUE="' . $fe['selector'] . '#' . $fee['catsubsel'] . '#' . $feee['catsubsubsel'] . '" SELECTED>' . $fe['category'] . ' / ' . $fee['subcategory'] . ' / ' . $feee['subsubcategory'] . '</OPTION>';
     if (($feee['catsubsubsel'] == 0) and ($fee['catsubsel'] != 0))
       $in_location .= '<OPTION VALUE="' . $fe['selector'] . '#' . $fee['catsubsel'] . '#0" SELECTED>' . $fe['category'] . ' / ' . $fee['subcategory'] . '</OPTION>';
     if (($feee['catsubsubsel'] == 0) and ($fee['catsubsel'] == 0))
       $in_location .= '<OPTION VALUE="' . $fe['selector'] . '#0#0" SELECTED>' . $fe['category'] . '</OPTION>';
	}
     else {
      if (($feee['catsubsubsel'] != 0) and ($fee['catsubsel'] != 0))
	  $in_location .= '<OPTION VALUE="' . $fe['selector'] . '#' . $fee['catsubsel'] . '#' . $feee['catsubsubsel'] . '">' . $fe['category'] . ' / ' . $fee['subcategory'] . ' / ' . $feee['subsubcategory'] . '</OPTION>';
      if (($feee['catsubsubsel'] == 0) and ($fee['catsubsel'] != 0))
	  $in_location .= '<OPTION VALUE="' . $fe['selector'] . '#' . $fee['catsubsel'] . '#0">' . $fe['category'] . ' / ' . $fee['subcategory'] . '</OPTION>';
      if (($feee['catsubsubsel'] == 0) and ($fee['catsubsel'] == 0))
	  $in_location .= '<OPTION VALUE="' . $fe['selector'] . '#0#0">' . $fe['category'] . '</OPTION>';
     }

    }

   }

  }

  @mysql_free_result ( $re );
  @mysql_free_result ( $ree );
  @mysql_free_result ( $reee );

   $in_location .= '</SELECT>';

  // ==

  echo userform ($lang['Location'], $in_location);

  if (strcasecmp(@$conf['show_postal_code'], 'OFF') != 0) {
    echo userform ($lang['Zip_Code'], '<input type="text" size="45" name="zip" maxlength="50">');
  }
  echo userform ($lang['Listing_Address1'], '<input type="text" size="45" name="address1" maxlength="50">');
  echo userform ($lang['Listing_Address2'], '<input type="text" size="45" name="address2" maxlength="50">');
  echo userform ($lang['Listing_Directions'], '<input type="text" size="45" name="directions" maxlength="50">');
  echo userform ($lang['Listing_Year_Built'], '<input type="text" size="45" name="year_built" maxlength="4">');
  echo userform ($lang['Listing_Additional_Out_Buildings'], generate_checkbox_list(BUILDINGS_TABLE, 'buildings'));
  echo userform ($lang['Listing_Appliances_Included'], generate_checkbox_list(APPLIANCES_TABLE, 'appliances'));
  echo userform ($lang['Listing_Features'], generate_checkbox_list(FEATURES_TABLE, 'features'));
  echo userform ($lang['Listing_Garage'], '<select name="garage"><option value="ANY">' . $lang['Search_Any'] . '</option>' . generate_options_list(GARAGE_TABLE) . '</select>');
  echo userform ($lang['Listing_Garage_Cars'], '<input type="text" size="45" name="garage_cars" maxlength="2">');
  echo userform ($lang['Listing_Basement'], '<select name="basement"><option value="ANY">' . $lang['Search_Any'] . '</option>' . generate_options_list(BASEMENT_TABLE) . '</select>');
  
  $price_range = '';
  for ($i = $conf['price_range_min']; $i <= $conf['price_range_max']; $i = $i + $conf['price_range_step'])
  $price_range.= '<option value="' . $i . '">' . $conf['currency'] . ' ' . $i . '</option>' . "\n";
 
  echo userform ($lang['Search_Price_Range'], '
         <select name="price_min">
 	 <option value="ANY">' . $lang['Search_Any'] . '</option>
         ' . $price_range . '
         </select>');
 
  echo userform ('', '
 
         <select name="price_max">
 	 <option value="ANY">' . $lang['Search_Any'] . '</option>
         ' . $price_range . '
         </select>');
 
  echo userform ('', '<input type="Submit" name="property_search" value="' . $lang['Property_Search'] . '">');
 
  echo '
    </table>
   </form>
       ';
 
  echo table_footer ();
 
 }
 
else

 error ('Critical Error' , 'Please, login to access this script.');

// template footer
include ( PATH . '/admin/template/footer.php' );

?>